// @include "sprite.js"
// @include "frame.js"

qinglan.Canvas.Frame = qinglan.Canvas.Class(function(canvasId,frames) {
	/**
	 * 帧宽度
	 * 
	 * @field
	 */
	this.FrameX = qinglan.Canvas.Config.frameWidth;
	/**
	 * 帧高度
	 * 
	 * @field
	 */
	this.FrameY = qinglan.Canvas.Config.frameHeight;
	/**
	 * loop对象
	 * 
	 * @field
	 */
	this.loop = null;
	/**
	 * 
	 */
	this.Frames = qinglan.Canvas.Config.frames;
	/**
	 * layers数组
	 * 
	 * @field
	 */
	this.layers = {};

	this.isPlay = false;

	this.zIndexBox = [];
	/**
	 * canvas缓存对象 
	 */
	this.canvasNode = document.getElementById(canvasId);
	this.FrameX = this.canvasNode.width;
	this.FrameY = this.canvasNode.height;
	
	this.ctx = this.canvasNode.getContext('2d');

	this.bufferCanvas = document.createElement('canvas');
	this.bufferCanvas.width = this.FrameX;
	this.bufferCanvas.height = this.FrameY;
	this.bufferCtx = this.bufferCanvas.getContext('2d');

}).methods({
	/**
	 * 开始动画
	 * 
	 * @property
	 * @public
	 */
	start : function() {
		if(this.isPlay) {return false;}
		this.loop ? this.loop.resume() : (this.loop = new qinglan.Canvas.Loop(this.render,this));
		this.isPlay = true;
		return ;
		/*var self = this;
		var render = function(){
			self.render();
			requestAnimationFrame(render);
		}
		render();
		// this.interval = setInterval((function(param) {
		// 			return function() {
		// 				param.render();
		// 			};
		// 		})(this), 1000/this.Frames);
		*/
	},
	/**
	 * 停止动画
	 * 
	 * @property
	 * @public
	 */
	stop : function() {
		if(!this.isPlay) {return false;}
		this.loop.stop();
		this.isPlay = false;
	},
	/**
	 * 进行渲染
	 * 
	 * @property
	 * @public
	 */
	render : function() {
		//if(!this.isPlay) {return false;}
		qinglan.Object.each(this.layers,function(layer){
			layer.render(this.ctx);
		});
		this.clearFrame(this.bufferCtx);
		qinglan.Object.each(this.zIndexBox,function(layers){
			if(layers){
				qinglan.Object.each(layers,function(layer){
					this.bufferCtx.drawImage(layer.getCanvas(),layer.offset.x,layer.offset.y);
				},this);
			}
		},this);

		this.clearFrame();
		this.ctx.drawImage(this.bufferCanvas,0,0);
		qinglan.Canvas.World.frames++;
	},
	/**
	 * 添加动画元素
	 * 
	 * @property
	 * @public
	 */
	addLayer : function(layer) {
		this.layers[layer.id] = layer;
		var zindex = layer.zIndex;
		var box = this.zIndexBox[zindex];
		!box && (box = this.zIndexBox[zindex] = []);
		box.push(layer);
	},
	getLayer: function(id){
		return this.layers[id];
	},
	clearFrame : function(ctx){
		var ctx = ctx || this.ctx;
		qinglan.Canvas.CanvasRender.clear(ctx, this.FrameX, this.FrameY);
	},
	/**
	 * 清楚画板
	 * 
	 * @property
	 * @public
	 */
	destroy : function() {
		qinglan.Object.each(this.layers,function(layer){
			layer.destroy();
		});
	}
});
